﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Text;
using TcpClient.Core.SqlSugar;
using TcpClient.Web.Core.Log;
using TcpClient.Web.Core.Result;

namespace TcpClient.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            // 默认授权机制，需授权的即可（方法）需贴 `[Authorize]` 特性
            services.AddJwt<JwtHandler>();

            services.AddCorsAccessor();

            // Json序列化设置
            static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
            {
                setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
                //setting.Converters.AddDateTimeTypeConverters(localized: true); // 时间本地化
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
                setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
                                                                              // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
                                                                              // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
                                                                              // setting.Converters.AddLongTypeConverters(); // long转string（防止js精度溢出） 超过17位开启
                                                                              // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
                                                                              // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
                                                                              // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
            };



            //services.AddMvcFilter<LoggingMonitorAttribute>();
            //日志
            services.AddMonitorLogging();
            // 日志写入数据库
            if (App.GetConfig<bool>("Logging:Database:Enabled", true))
            {
                services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
                {
                    options.WithTraceId = true; // 显示线程Id
                    options.WithStackFrame = true; // 显示程序集
                    options.IgnoreReferenceLoop = false; // 忽略循环检测
                    options.MessageFormat = (logMsg) =>
                    {
                        var stringBuilder = new StringBuilder();
                        stringBuilder.AppendLine(logMsg.Message);
                        return stringBuilder.ToString();
                    };
                    //options.WriteFilter = (logMsg) =>
                    //{
                    //    return logMsg.LogName == CommonConst.SysLogCategoryName; // 只写LoggingMonitor日志
                    //};
                });
            }

            // 添加 TCP 客户端后台服务
           // services.AddHostedService<TcpClientBackgroundService>();

            services.AddSqlsugarSetup();


            services.AddControllers()
                    .AddInjectWithUnifyResult<YourRESTfulResultProvider>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
